"""
学习分析模块信号处理
"""
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.utils import timezone
from django.contrib.contenttypes.models import ContentType
from .models import LearningActivity, LearningAnalytics


@receiver(post_save, sender=LearningActivity)
def update_user_analytics(sender, instance, created, **kwargs):
    """更新用户学习分析数据"""
    if created:
        user = instance.user
        today = timezone.now().date()

        # 更新每日学习活动统计
        analytics, created = LearningAnalytics.objects.get_or_create(
            user=user,
            analysis_type=LearningAnalytics.AnalysisType.DAILY,
            period_start=today,
            period_end=today,
            defaults={
                'activity_count': 1,
                'total_study_time': instance.duration or 0,
            }
        )

        if not created:
            analytics.activity_count += 1
            if instance.duration:
                analytics.total_study_time += instance.duration
            analytics.save(update_fields=['activity_count', 'total_study_time'])